<template>
  <div
    class="swiper-container"
    ref="swiper"
    @mouseenter="swiper.autoplay.stop()"
    @mouseleave="swiper.autoplay.start()"
  >
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="(image,index) in imageList" :key="image.id">
        <!-- 懒加载跟swiper一起用，循环会出现问题，下面是解决方案 -->
        <img v-if="index===0||index===imageList.length-1" :src="image.imgUrl" :alt="image.id" />
        <img v-else v-lazy="image.imgUrl" :alt="image.id" />
      </div>
    </div>
    <!-- 分页器 -->
    <div class="swiper-pagination"></div>

    <!-- 导航按键 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>

    <!-- 滚动条 -->
    <!-- <div class="swiper-scrollbar"></div> -->
  </div>
</template>

<script>
import Swiper from "swiper";
import "swiper/css/swiper.min.css";

export default {
  name: "Carousel",
  props: {
    imageList: {
      type: Array,
      required: true,
    },
  },
  watch: {
    imageList: {
      //当imageList值改变了，就会触发$nextTick(),只有在imageList有值的时候再去new Swiper才有用
      handler(imageList) {
        if (!imageList.length) return;
        this.$nextTick(() => {
          this.swiper = new Swiper(this.$refs.swiper, {
            loop: true, // 循环模式选项
            direction: "horizontal", //切换方向
            speed: 1000, //切换速度
            grabCursor: true, //光标为捕捉
            autoplay: true, //自动播放

            // 如果需要分页器
            pagination: {
              el: ".swiper-pagination",
            },

            // 如果需要前进后退按钮
            navigation: {
              nextEl: ".swiper-button-next",
              prevEl: ".swiper-button-prev",
            },
          });
        });
      },
      immediate: true,
    },
  },
};
</script>

<style lang="less" scoped>
</style>